package com.smarthome.ipc.aopu;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.smarthome.domain.ipc.IpcConstants;
import com.smarthome.ipc.aopu.entity.AopuDoorOpen;

@Service
public class AopuTcpMain {

	private AopuTcpMain() {
	}

	public void sendCommand(AopuDoorOpen request) throws Exception {
		if (StringUtils.isNotBlank(request.getAccessType())
				&& IpcConstants.IPC_ACCESS_TYPE_OUTERNETWORK.equals(request.getAccessType())) {
			AopuTcpCorrespondence.doCommand(request.getCommandhex(), request.getDoorNum(), request.getLengthL(),
					request.getLengthH(), request.getData(), request.getIp(), request.getPort());
		} else {
			StringBuilder ul = new StringBuilder("http://");
			ul.append(request.getIp());
			ul.append("/cdor.cgi?open=1");
			URL url = new URL(ul.toString());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("Authorization", "Basic YWRtaW46ODg4ODg4");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.connect();

			conn.getInputStream();
			StringBuilder sb = new StringBuilder();
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String inputLine = "";
			while ((inputLine = in.readLine()) != null) {
				sb.append(inputLine);
			}
			in.close();
//			System.out.println(sb.toString());

		}

	}

	// @PostConstruct
	@SuppressWarnings("unused")
	private void openConnection() throws Exception {
		new Thread(new Runnable() {

			public void run() {
				while (true) {
					AopuTcpCorrespondence.receiveCommand();
				}
			}
		}).start();
	}

}